from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from lib.common import AbstractHandler
import logging
app_logger = logging.getLogger("student")
import json
from django.core.cache import cache
from services.asyntask import (tencent_imcallback_task, tencent_peopleflow_task)
import traceback
import re

class Handler(AbstractHandler):

    def __init__(self):
        AbstractHandler.__init__(self, app_logger)

    @csrf_exempt
    def handle_cloud_im_notify(self, request):
        try:
            im_notify = json.loads(request.body)
            # app_logger.error("im的回调")
            # app_logger.error(im_notify)
            command = im_notify['CallbackCommand']
            if str(command) == "Group.CallbackBeforeSendMsg":
                group_id = im_notify['GroupId']
                if im_notify['MsgBody']:
                    # user_id = []
                    # group_id_arr = []
                    for v in im_notify['MsgBody']:
                        if str(v['MsgType']) == "TIMCustomElem":
                            type = json.loads(v['MsgContent']['Data'])
                            if 'command' in type.keys() and int(type['command']) == 4:  # 自定义消息 like:点赞 4
                                user_id = json.loads(cache.get('live_user_id_'+str(group_id), '[]'))
                                group_id_arr = json.loads(cache.get('live_group_id', '[]'))

                                if not cache.get('user_like_'+str(im_notify['From_Account'])+'_'+str(group_id)):
                                    cache.set('user_like_'+str(im_notify['From_Account'])+'_'+str(group_id), 1, 3600*24)
                                    user_id.append(im_notify['From_Account'])
                                else:
                                    cache.incr('user_like_'+str(im_notify['From_Account'])+'_'+str(group_id), 1)
                                # 根据收到的点赞/关注消息数进行数量统计
                                # if not cache.get(str(group_id)+'_like'):
                                #     cache.set(str(group_id)+'_like', 1)
                                # else:
                                #     cache.incr(str(group_id)+'_like', 1)
                                if group_id not in group_id_arr:
                                    group_id_arr.append(group_id)
                                # 记录点赞用户的id
                                cache.set('live_user_id_'+str(group_id), json.dumps(user_id), 3600*24*1)
                                cache.set('live_group_id', json.dumps(group_id_arr), 3600*24*1)
                            # if str(v['MsgContent']['Data']) == "on_click":  # 购物袋点击
                            #     cache.incr(str(group_id)+'_on_click', 1)
                            # if str(v['MsgContent']['Data']) == "share":  # 分享
                            #     cache.incr(str(group_id)+'_share', 1)

                            elif 'command' in type.keys() and int(type['command']) == 7:  # 这里这个定义特殊--用于分享链接进来的用户绑定
                                share_u = json.loads(v['MsgContent']['Data'])  # {'share_code': '', 'user_id': 1}
                                tencent_imcallback_task.add_share_user.delay(group_id=group_id, share_data=share_u)
                            # 用于新用户进入直播间发送推荐商品，发送浏览量
                            elif type.get('command') and type.get('message') and int(type['command']) == 12 and int(type['message']) == 4:
                                tencent_imcallback_task.send_pv_and_goods(group_id)
                            # 记录主播端推荐商品
                            elif type.get('command') and int(type['command']) == 9:
                                cache.set(f"{group_id}_push_goods", type.get('message'), 3600 * 24)

            if str(command) == "Group.CallbackAfterSendMsg":
                tencent_imcallback_task.handle_user_send_msg.delay(user_id=int(im_notify['From_Account']),
                                                                   group_id=im_notify['GroupId'],
                                                                   msg_time=im_notify['MsgTime'],
                                                                   msg_seq=im_notify['MsgSeq'],
                                                                   msg_body=im_notify['MsgBody'])
            if str(command) == "Group.CallbackAfterNewMemberJoin":  # 新成员入群之后回调
                tencent_peopleflow_task.handle_peopleflow_join.delay(group_id=im_notify['GroupId'],
                                                                     users=im_notify['NewMemberList'],
                                                                     times=im_notify['EventTime'])
            if str(command) == "Group.CallbackAfterMemberExit":  # 群成员离开之后回调
                tencent_peopleflow_task.handle_peopleflow_exit.delay(group_id=im_notify['GroupId'],
                                                                     users=im_notify['ExitMemberList'],
                                                                     times=im_notify['EventTime'])
            if str(command) == "Group.CallbackAfterGroupDestroyed": # 群组解散之后回调
                pass
        except:
            err = traceback.format_exc()
            app_logger.error(err)
        return JsonResponse({"ActionStatus": "OK", "ErrorInfo": "", "ErrorCode": 0})

    @csrf_exempt
    def handle_cloud_trtc_notify(self, request):
        """
        {'EventGroupId': 1, 'EventType': 103, 'CallbackTs': 1637119407447, 'EventInfo': {'RoomId': 355656221,
        'EventTs': 1637119407, 'EventMsTs': 1637119407419, 'UserId': '8481', 'Role': 20, 'TerminalType': 2,
        'UserType': 3, 'Reason': 1}}
        {'EventGroupId': 2, 'EventType': 203, 'CallbackTs': 1637119407768, 'EventInfo': {'RoomId': 355656221,
        'EventTs': 1637119407, 'EventMsTs': 1637119407754, 'UserId': '8481'}}
        :param request:
        :return:
        """
        # app_logger.error(json.loads(request.body))
        notify_data = json.loads(request.body)
        if not notify_data:
            pass
        if notify_data['EventGroupId'] == 1:  # 房间事件组
            #  这里将加入房间的用户
            if notify_data['EventType'] == 103:
                # tencent_imcallback_task.handle_user_join_room.delay(user_id=int(notify_data['EventInfo']['UserId']),
                #                                                     group_id=notify_data['EventInfo']['RoomId'])
                pass
            if notify_data['EventType'] == 104:  # 退出房间
                # 主播异常退出房间 5:强杀  2:超时退出
                reason = notify_data['EventInfo'].get('Reason')
                if notify_data['EventInfo'].get('Role') == 20 and (reason == 5 or reason == 2):
                    # res = tencent_imcallback_task.handle_strong_regression_room(
                    #     group_id=notify_data['EventInfo']['RoomId']
                    # )
                    pass
            if notify_data['EventType'] == 102:  # 解散房间
                tencent_imcallback_task.handle_dismiss_room.delay(group_id=notify_data['EventInfo']['RoomId'],
                                                                  msg_time=notify_data['EventInfo']['EventTs'])

        if notify_data['EventGroupId'] == 2:  # 媒体事件组
            if notify_data['EventType'] == 201:  # 开始推送视频数据
                tencent_imcallback_task.handle_trtc_start_video.delay(status=2, room_id=notify_data['EventInfo']['RoomId'])
            if notify_data['EventType'] == 202:
                tencent_imcallback_task.handle_trtc_start_video.delay(status=2, room_id=notify_data['EventInfo']['RoomId'])
        return JsonResponse({"code": 0})

    @csrf_exempt
    def handle_cloud_live_playback(self, request):
        live_notify = json.loads(request.body)
        app_logger.error("直播录制的回调")
        app_logger.error(live_notify)
        room_id = re.findall(r'groupid=(\d+)', live_notify['stream_param'])[0]
        tencent_imcallback_task.get_live_playback.delay(live_notify, room_id)
        return JsonResponse({"code": 0, "ActionStatus": "OK", "ErrorInfo": "", "ErrorCode": 0})

    @csrf_exempt
    def handle_cloud_live_notify(self, request):
        from services.datamodel.live.models import mm_Live
        notify_data = json.loads(request.body)
        if not notify_data:
            return JsonResponse({"code": 0, "ActionStatus": "OK", "ErrorInfo": "", "ErrorCode": 0})
        app_logger.error("进入推流直播回调")
        app_logger.error(notify_data)
        live_id = notify_data['stream_id'].split("_")[0]
        l = mm_Live.filter(pk=live_id).first()
        # 推流
        if notify_data['event_type'] == 1:
            tencent_imcallback_task.handle_trtc_start_video.delay(status=2, room_id=l.room_id)
        # 断流
        elif notify_data['event_type'] == 0:
            tencent_imcallback_task.handle_dismiss_room.delay(group_id=l.room_id, msg_time=None)
        # 录制
        elif notify_data['event_type'] == 100:
            tencent_imcallback_task.get_live_playback.delay(notify_data, l.room_id)
        return JsonResponse({"code": 0, "ActionStatus": "OK", "ErrorInfo": "", "ErrorCode": 0})

im_handler = Handler()